<?php
/**
  * wechat php test
  */
require_once './config.php';
require_once './log.php';
require DZ_ROOT . 'class_core.php';
ini_set("log_errors", 1);

$discuz = C::app();
#Pass xss check
if($_SERVER['REQUEST_METHOD'] !== 'GET') {
	$_GET['formhash'] = formhash();
}
$discuz->init();

require_once './class/WeChat/WeChatValidation.php';
require_once './class/WeChat/WeChatMessage.php';
require_once './class/Discuz/DiscuzUserDAO.php';
require_once './class/WeChat/WeChatService.php';
require_once './class/Discuz/DiscuzThreadDAO.php';

$wechatObj = new WeChatValidation();
$service = new WeChatService();
$userDao = new DiscuzUserDAO();
$threadDao = new DiscuzThreadDAO();

if($wechatObj->checkSignature()) {
    msg("Event message passed signature check");
    if(!is_null($wechatObj->echoString())) {
        msg("This is a hand shake message");
        echo($wechatObj->echoString());
    } else {
        $msg = new WeChatMessage();
        if(!is_null($msg->retrieveMsg())) {
        	$msg->userInfo = $userDao->getDZUser($msg->user);
        	if(is_null($msg->userInfo)) {       		
        		$remoteInfo = $service->getUserInfo($msg->user);
        		if(!is_null($remoteInfo)) {
        			msg("Get user info");
        			$msg->userInfo = $userDao->createDZUser($remoteInfo);
        		} else {
        			msg("Can't get user info");
        		}
        	}
        	$fileNames = array($msg->message['MsgType']);
        	if(isset($msg->message['Event']))
        		array_push($fileNames, $msg->message['Event']);
        	if(isset($msg->message['EventKey']))
        		array_push($fileNames, $msg->message['EventKey']);
            $handler = './handlers/' . join("_", $fileNames) . ".php";
            msg("Load php file " . $handler);
            require $handler;
        }
    }
} else {
    msg("Event message doesn't pass signature check. Drop it!");
}

?>
